package com.qufadai.btce.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.codec.binary.Hex;


public class HttpConnectionUtil {

	public static String executeHttpGet(String url)
			throws MalformedURLException, IOException {
		boolean isSSL = url.toUpperCase().indexOf("HTTPS://") > -1;
		if (isSSL) {
			setTrustSSLContent();
		}
		HttpURLConnection conn = (HttpURLConnection) new URL(url)
				.openConnection();
		conn.setRequestMethod("GET");
		conn.setRequestProperty("User-agent",
				"Mozilla/9.0 (compatible; MSIE 10.0; Windows NT 8.1; .NET CLR 2.0.50727)");
		byte[] buf = new byte[1024 * 1024];
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
		int len = -1;
		while ((len = in.read(buf)) > 0) {
			byteOut.write(buf, 0, len);
		}
		in.close();
		conn.disconnect();
		byteOut.flush();
		byte[] responseData = byteOut.toByteArray();

		return new String(responseData, getEncoding(conn, responseData)).trim();
	}

	public static String executeHttpsPost(String url, byte[] postData)
			throws Exception {
		X509TrustManager trustManager = new X509TrustManager() {
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
		};
		X509TrustManager[] tm = new X509TrustManager[] { trustManager };
		// SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, tm, new java.security.SecureRandom());
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		HttpsURLConnection conn = (HttpsURLConnection) new URL(url)
				.openConnection();

		conn.setSSLSocketFactory(ssf);
		conn.setHostnameVerifier(new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		});

		conn.setRequestMethod("POST");
		conn.setRequestProperty("User-agent",
				"Mozilla/9.0 (compatible; MSIE 10.0; Windows NT 8.1; .NET CLR 2.0.50727)");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length",
				String.valueOf(postData.length));
		byte[] sign = SHATools.encodeHmacSHA512(postData,
				Constant.BTCE_SECRET.getBytes("UTF-8"));
		String signHexString = Hex.encodeHexString(sign);
		System.out.println("Key:" + Constant.BTCE_KEY);
		System.out.println("Sign:" + signHexString);
		conn.addRequestProperty("Key", Constant.BTCE_KEY);
		conn.addRequestProperty("Sign", signHexString);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.connect();
		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.flush();
		byte[] buf = new byte[1024 * 1024];
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
		int len = -1;
		while ((len = in.read(buf)) > 0) {
			byteOut.write(buf, 0, len);
		}
		// in.close();
		// conn.disconnect();
		byteOut.flush();
		byte[] responseData = byteOut.toByteArray();

		return new String(responseData, getEncoding(conn, responseData)).trim();
	}

	private static String getEncoding(HttpURLConnection conn, byte[] data) {
		String encoding = "ISO-8859-1";
		String contentEncoding = conn.getContentEncoding();
		String contentType = conn.getContentType();
		if (contentEncoding != null && contentEncoding.trim().length() > 0) {
			encoding = contentEncoding;
		} else if (contentType != null) {
			contentType = contentType.toUpperCase();
			if (contentType.contains("UTF")) {
				encoding = "UTF-8";
			} else if (contentType.contains("GBK")) {
				encoding = "GBK";
			} else if (contentType.contains("GB2312")) {
				encoding = "GB2312";
			}
		}
		return encoding;
	}

	public static void setTrustSSLContent() {
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}

			public void checkServerTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}
		} };
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
		}
	}
}